<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
 # Set the various components and helpers to use.
    public $helpers = array(
        'Js', 'Html', 'Form', 'Session','Select'
    );

    public $global_var = array();
	
	public $currency_types = array();
    public $payment_types = array();
    public $customer_types = array();
    public $buying_usd_rate = 0.00;
    public $selling_usd_rate = 0.00;
    public $print_statement = '';
    public $proforma_account_no = '';
    public $proforma_credit_statement = '';
    public $proforma_outright_statement = '';

    public $components = array(
        'RequestHandler', 'Session',
        //'Security' => array(
        //'csrfUseOnce' => false
        //'csrfCheck' => false
        //  ),
        'Auth' => array(
            'loginAction' => array('controller' => 'Users', 'action' => 'login'),
            'loginRedirect' => array('controller' => 'Dashboard', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
        )
    );


    function beforeFilter($moduleName = null)
    {
        $authUser = $this->Auth->user();
        $Group = ClassRegistry::init('Group');
        //$group = $Group->getGroupById($authUser['group_id']);
        $group = $Group->find('first', array(
            'conditions'=>array('Group.id'=>$authUser['group_id']),
            'recursive' => -1
        ));

        //Your messages

        $MessageReciever = ClassRegistry::init('MessageReciever');
        //$group = $Group->getGroupById($authUser['group_id']);
        $user_inbox = $MessageReciever->find('count',array(
            'conditions'=>array('MessageReciever.user_id'=>$authUser['id'], 'MessageReciever.msg_status'=>'unread','MessageReciever.trash'=>'n'),
            'recursive'=>-1
        ));
        $group = $Group->find('first', array(
            'conditions'=>array('Group.id'=>$authUser['group_id']),
            'recursive' => -1
        ));

        $this->set(compact('authUser','group','user_inbox'));

        /*if ($this->Auth->user()) {
            if ($moduleName != null) {
                // If you are not assigned a model, then u can't use'
                $ModelObj = ClassRegistry::init('Group');
                $userData = $ModelObj->getGroupById($this->Auth->user('group_id'));
                $userModules = $userData['Module'];
                $allowed = false;
                foreach ($userModules as $module) {
                    if ($module['name'] === $moduleName) {
                        $allowed = true;
                    }
                }
                if (!$allowed) {
                    $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
                }
            }
        }*/
    }


    function blackhole($type)
    {
        // handle errors.
        if ($type == 'auth') {
            $errors = array('code' => 1, 'mesg' => __(' Form Validation Error Or Controller/action mismatch '));
        }
        else if ($type == 'csrf') {
            $errors = array('code' => 1, 'mesg' => __(' Cross Site Request Forgery '));
        }
        else if ($type == 'get') {
            $errors = array('code' => 1, 'mesg' => __(' HTTP GET method restriction failure '));
        }
        else if ($type == 'post') {
            $errors = array('code' => 1, 'mesg' => __(' HTTP POST method restriction failure '));
        }
        else if ($type == 'put') {
            $errors = array('code' => 1, 'mesg' => __(' HTTP PUT method restriction failure '));
        }
        else if ($type == 'delete') {
            $errors = array('code' => 1, 'mesg' => __(' HTTP DELETE method restriction failure or  SSL method restriction failure'));
        }

        return $errors;
    }

   function  setUpGlobalConfig(){
        #Setting Up the systems Global Configuration
        $globalConfigObj = ClassRegistry::init('Configuration');
        # List of all the modules in the system
        $allGlobalConfiguration = $globalConfigObj->find('all', array('recursive' => -1, 'order' => 'Configuration.key ASC'));

        $new_global_config_array = array();

        foreach ($allGlobalConfiguration as $array_data) {
            $new_globalkey = $array_data['Configuration']['key'];
            $new_globalvalue = $array_data['Configuration']['value'];

            $new_global_config_array[$new_globalkey] = $new_globalvalue;
        }

        /** Initializing the global Constants*/

        $global_currency_value = $new_global_config_array['currency_inuse'];
        $global_payment_types = $new_global_config_array['payment_type'];
        $global_customer_types = $new_global_config_array['customer_types'];
        $this->buying_usd_rate = $new_global_config_array['buying_usd_rate'];
        $this->selling_usd_rate = $new_global_config_array['selling_usd_rate'];
        $this->print_statement = $new_global_config_array['print_statement'];
        $this->proforma_account_no = $new_global_config_array['proforma_account_no'];
        $this->proforma_credit_statement = $new_global_config_array['proforma_credit_statement'];
        $this->proforma_outright_statement = $new_global_config_array['proforma_outright_statement'];

        //define('CURRENCY',$global_currency_value);
        $pay_type_arr = explode('#', $global_payment_types);
        foreach ($pay_type_arr as $type_opt) {
            $this->payment_types[$type_opt] = $type_opt;
        }

        $cus_type_arr = explode('#', $global_customer_types);
        foreach ($cus_type_arr as $type_opt) {
            $this->customer_types[$type_opt] = $type_opt;
        }

        $curr_type_arr = explode('#', $global_currency_value);
        foreach ($curr_type_arr as $type_opt) {
            $this->currency_types[$type_opt] = $type_opt;
        }
    }


    function covertDate($date = null, $type = 'mysql')
    {
        $res = '';
        if(empty($date)){

        }
        elseif($type == 'mysql'){
            $res =  date("Y-m-d", strtotime($date));
        }
        elseif($type == 'ui'){
            $res =  date("F d, Y", strtotime($date));
        }
        return $res;
    }


    function count_months_between_dates($smaller_date, $bigger_date)
    {
        $d1 = strtotime($smaller_date); //Smaller
        $d2 = strtotime($bigger_date); //Bigger
        $min_date = min($d1, $d2);
        $max_date = max($d1, $d2);
        $i = 0;
        while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
            $i++;
        }
        return $i;
    }


    function formatNumber($value = 0, $type = 'number', $decimal_place = 2)
    {
        if ($type == 'money') {
            $num = number_format($value, $decimal_place, '.', ',');
        }
        else {
            $num = number_format($value, $decimal_place, '.', '');
        }

        return $num;
    }

    function getRate($rate = 0, $tenor = 1, $decimal_places = 4)
    {
        $r = (doubleval($rate) / 100) / (intval($tenor) * 12); //interest rate per period
        //$r = (doubleval($rate)/100); //interest rate per period
        $r = $this->formatNumber($r,'number',$decimal_places);
        return $r;
    }

    function getMonthlyPayment($rate = 0, $duration = 0, $loan = 0, $tenor = 1, $ratio_decimal_places=4, $purchase_type="Interest Payment")
    {
        $A = 0; //payment Amount per period
        $P = $loan; //initial Principal (loan amount)
        $r = $this->getRate($rate, $tenor,$ratio_decimal_places);//interest rate per period
        $n = $duration; //total number of payments or periods

        if($purchase_type == 'Non Interest Payment'){
            //$A = $this->formatNumber($loan / $duration, 'number');
            $A = $P / $n;
        }
        else{
            $numerator = ($r * pow((1 + $r), $n));
            $denominator = (pow((1 + $r), $n) - 1);
            if($denominator == 0){
                $denominator = 1;
            }
            $A = $P * ( $numerator / $denominator);
        }

        return $A;
    }


    function getDiscountAmount($cost = 0, $discount = 0)
    {

        $C = doubleval($cost);
        $Dc = doubleval($discount);
        $r = ($Dc) / 100;
        $A = $r * $C;
        return $A;
    }

    function getPrincipal($cost = 0, $discount = 0, $deposit = 0)
    {

        $C = doubleval($cost);
        $Dc = $this->getDiscountAmount($cost, $discount);
        $Dp = doubleval($deposit);

        $A = $C - $Dc - $Dp;

        return $A;
    }

    function get_amortization_data($id = null)
    {
        ClassRegistry::init('Sale');
        /** Loading */
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit', 'Sale.discount', 'Sale.payment_type', 'Sale.currency', 'Sale.comments'),
            'conditions' => array('Sale.id' => $id),
            'contain' => array(
                'Customer',
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id', 'SaleItem.quantity'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount', 'SaleCreditPayment.pay_date'),
                )
            ),
            'recursive' => 2
        ));

        $vehicle_no = $data['Sale']['vehicle_no'];
        $currency = $data['Sale']['currency'];
        $opening_bal = doubleval($data['Sale']['opening_bal']);
        $purchase_type = $data['Sale']['purchase_type'];

        //IF the customer made outright payment
        if($opening_bal == $data['Sale']['deposit']){
            $opening_bal = 0.00;
        }
        $duration_in_month = intval($data['Sale']['duration_in_month']);
        $interest = doubleval($data['Sale']['interest']);
        $interest_ratio = $this->getRate($interest, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places']);

        $mth_inst = $this->getMonthlyPayment($interest, $duration_in_month, $opening_bal, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places'],$purchase_type);

        // Building the amortization data
        $new_opbl = $opening_bal;
        $amor = array();

        $row = array();
        $row['period'] = '';
        $row['payment_amount'] = '';
        $row['inerest'] = '';
        $row['principal'] = '';
        $row['balance'] = $currency . " " . $this->formatNumber($new_opbl, 'money');
        $amor[] = $row;

        $tl_interest_paid = 0.00;
        $tl_principal = 0.00;

        for ($x = 1; $x <= $duration_in_month; $x++) {
            $payment_amount = $mth_inst;
            $inerest = $new_opbl * $interest_ratio;
            $principal = $payment_amount - $inerest;
            $balance = $bal1 = $new_opbl - $principal;
            $bal1 = $this->formatNumber($bal1);

            if ($bal1 == -0.0) {
                $balance = 0.0;
            }

            $tl_interest_paid = $tl_interest_paid + $inerest;
            $tl_principal = $tl_principal + $principal;

            $row = array();
            $row['period'] = $x;
            $row['payment_amount'] = $this->formatNumber($mth_inst, 'money');
            $row['inerest'] = $this->formatNumber($inerest, 'money');
            $row['principal'] = $this->formatNumber($principal, 'money');
            $row['balance'] = $this->formatNumber($balance, 'money');

            $amor[] = $row;
            //Reset the new opening bal
            $new_opbl = $balance;
        }

        $json_data = array();
        $json_data['data'] = $amor;
        $json_data['tl_inerest'] = $this->formatNumber($tl_interest_paid, 'money');
        $json_data['tl_inerest_raw'] = $this->formatNumber($tl_interest_paid);
        $json_data['tl_principal'] = $this->formatNumber($tl_principal);
        $json_data['currency'] = $currency;
        $json_data['opening_bal'] = $this->formatNumber($opening_bal, 'money');
        $json_data['opening_bal_raw'] = $this->formatNumber($opening_bal);
        $json_data['duration_in_month'] = $duration_in_month;
        $json_data['interest_ratio'] = $interest_ratio * 100;
        $json_data['monthly_inst'] = $this->formatNumber($mth_inst, 'money');
        $json_data['monthly_inst_raw'] = $this->formatNumber($mth_inst);
        $json_data['vehicle_no'] = $vehicle_no;
        $json_data['Sale'] = $data['Sale'];
        $json_data['Customer'] = $data['Customer'];


        return $json_data;
    }


    function get_repayment($data_id = null)
    {
        ClassRegistry::init('Sale');

        /** Loading */
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit', 'Sale.discount', 'Sale.payment_type', 'Sale.currency', 'Sale.comments'),
            'conditions' => array('Sale.id' => $data_id),
            'contain' => array(
                'Customer',
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id', 'SaleItem.quantity'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount', 'SaleCreditPayment.pay_date'),
                )
            ),
            'recursive' => 2
        ));

        $is_outright = false;
        $opening_bal = doubleval($data['Sale']['opening_bal']);
        $purchase_type = $data['Sale']['purchase_type'];
        //IF the customer made outright payment
        if($opening_bal == $data['Sale']['deposit']){
            $opening_bal = 0.00;
            $is_outright = true;
        }

        //Items
        $items = '';
        foreach ($data['SaleItem'] as $item) {
            $items .= $item['Item']['name'] . '(qty x' . $item['quantity'] . '),&nbsp;&nbsp;';
        }

        //Monthly Installments
        $duration_in_month = $data['Sale']['duration_in_month'];
        $vehicle_no = $data['Sale']['vehicle_no'];
        //$data['Sale']['opening_bal']
        // $mth_inst = (doubleval($data['Sale']['opening_bal'])) / intval($duration_in_month);
        //$mth_inst = number_format($mth_inst, 2, '.', '');

         $mth_inst = $this->getMonthlyPayment($data['Sale']['interest'], $duration_in_month, $opening_bal, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places'],$purchase_type);

        //Next month credit
        if ($data['SaleCreditPayment']) {
            $last_dt = $data['SaleCreditPayment'][0]['pay_date']; // this is sorted on id desc, so the first index[0] is the last paid date
        }
        else {
            $last_dt = $data['Sale']['purchased_date'];
        }
        $d = new DateTime($last_dt);
        $d->modify('next month');
        $next_credit_date = $d->format('Y-m-d');

        //Total Creidt Payment
        $totalpayment = 0.00;
        foreach ($data['SaleCreditPayment'] as $payment) {
            $totalpayment += doubleval($payment['paid_amount']);
        }

        // Outstanding balance
        $bal = (doubleval($opening_bal) - $totalpayment);

        if($is_outright){
            $purchase_dt = $data['Sale']['purchased_date'];
            $tl_expected = 0.00;
            $tl_actual = 0.00;
            $tl_outstanding = 0.00;
            $count = 1;

            $n_dt = new DateTime($purchase_dt);
            $month_year = $n_dt->format('M-y');
            $month_year2 = $n_dt->format('n-Y');
            $paid_amt = $this->formatNumber($data['Sale']['deposit']);
            $expected = $this->formatNumber($data['Sale']['opening_bal']);
            $outstanding = $this->formatNumber($expected - $paid_amt);
            $arr = array(
                $month_year,
                $this->__add_ordinal_suffix($count) . " month",
                $this->formatNumber($expected, 'money'),
                $this->formatNumber($paid_amt, 'money'),
                $this->formatNumber($outstanding, 'money')
            );
            $repayment[] = $arr;
            $arr2 = array(
                $month_year2,
                $this->formatNumber($expected),
                $this->formatNumber($paid_amt),
                $this->formatNumber($outstanding)
            );
            $rep_arr[] = $arr2;

            $tl_expected = $tl_expected + $expected;
            $tl_actual = $tl_actual + $paid_amt;
            $tl_outstanding = $tl_outstanding + $outstanding;


            $arr = array('', "<b>TOTAL</b>", "<b>" . $this->formatNumber($tl_expected, 'money') . "</b>", "<b>" . $this->formatNumber($tl_actual, 'money') . "</b>", "<b>" . $this->formatNumber($tl_outstanding, 'money') . "</b>");
            $repayment[] = $arr;
        }
        else{
            $repayment = array();
            $rep_arr = array();
            //Repayment formatting
            if ($duration_in_month > 0) { //Purchase date and end date are not the same
                $new_dt = new DateTime($data['Sale']['purchased_date']);
                $new_dt->modify('next month');
                $start_date = $new_dt->format('Y-m-d'); //Smaller date
                $end_date = $data['Sale']['end_date']; //Bigger date
                $diff_in_month = $this->count_months_between_dates($start_date, $end_date);
                $dates_arr = array($start_date);
                if ($diff_in_month > 0) {
                    $date_increment = $start_date;
                    for ($x = 1; $x <= $diff_in_month; $x++) {
                        $dt = new DateTime($date_increment);
                        $dt->modify('next month');
                        $dates_arr[] = $date_increment = $dt->format('Y-m-d');
                    }
                }

                $tl_expected = 0.00;
                $tl_actual = 0.00;
                $tl_outstanding = 0.00;
                $count = 1;
                foreach ($dates_arr as $date_str) {
                    $n_dt = new DateTime($date_str);
                    $rest = substr($date_str, 0, -3);
                    $amt_to_pay = 0.00;
                    foreach ($data['SaleCreditPayment'] as $payment) {
                        $y_m = substr($payment['pay_date'], 0, -3);
                        if ($rest == $y_m) {
                            $amt_to_pay = doubleval($payment['paid_amount']);
                        }
                    }
                    $month_year = $n_dt->format('M-y');
                    $month_year2 = $n_dt->format('n-Y');
                    $paid_amt = $this->formatNumber($amt_to_pay);
                    $expected = $this->formatNumber($mth_inst);
                    $outstanding = $this->formatNumber($mth_inst - $paid_amt);
                    $arr = array(
                        $month_year,
                        $this->__add_ordinal_suffix($count) . " month",
                        $this->formatNumber($expected, 'money'),
                        $this->formatNumber($paid_amt, 'money'),
                        $this->formatNumber($outstanding, 'money')
                    );
                    $repayment[] = $arr;
                    $arr2 = array(
                        $month_year2,
                        $this->formatNumber($expected),
                        $this->formatNumber($paid_amt),
                        $this->formatNumber($outstanding)
                    );
                    $rep_arr[] = $arr2;

                    $tl_expected = $tl_expected + $expected;
                    $tl_actual = $tl_actual + $paid_amt;
                    $tl_outstanding = $tl_outstanding + $outstanding;

                    $count++;
                }
                $arr = array('', "<b>TOTAL</b>", "<b>" . $this->formatNumber($tl_expected, 'money') . "</b>", "<b>" . $this->formatNumber($tl_actual, 'money') . "</b>", "<b>" . $this->formatNumber($tl_outstanding, 'money') . "</b>");
                $repayment[] = $arr;
            }
        }

        //debug($rep_arr);

        //find undue and past due
        $pastdue_amt = array();
        $undue_amt = array();
        //$now = strtotime(date('M-y'));
        $now_month = intval(date('n'));
        $now_year = intval(date('Y'));

        foreach ($rep_arr as $key => $value) {
            $dt_arr = explode('-', $value[0]);
            $dt_month = intval($dt_arr[0]);
            $dt_year = intval($dt_arr[1]);

            $topay = $value[1]; //amtpaid
            $amtpaid = floatval($value[2]); //amtpaid
            $outstanding_bal = floatval($value[3]); //
            //echo "$dt <= $now </ br>";
            if ($dt_year < $now_year) { //pastdue
                if ($amtpaid == 0.00) {
                    $pastdue_amt[] = $topay;
                }
                elseif($amtpaid > 0 ){
                    if($amtpaid == $topay){
                        $pastdue_amt[] = 0;
                    }
                    else{
                        $pastdue_amt[] = $outstanding_bal;
                    }
                }
            }
            elseif (($dt_year == $now_year)) {
                if (($dt_month < $now_month)) { //pastdue
                    if ($amtpaid == 0.00) {
                        $pastdue_amt[] = $topay;
                    }
                    elseif($amtpaid > 0 ){
                        if($amtpaid == $topay){
                            $pastdue_amt[] = 0;
                        }
                        else{
                            $pastdue_amt[] = $outstanding_bal;
                        }
                    }
                }
                elseif (($dt_month >= $now_month) && $amtpaid == 0.00) { //undue
                    $undue_amt[] = $topay;
                }
            }
            else { //undue
                if ($amtpaid == 0.00) {
                    $undue_amt[] = $topay;
                }
            }
        }

        $tl_pastdue = array_sum($pastdue_amt);
        $tl_undue = array_sum($undue_amt);

        $json_data = $data;
        $json_data['Sale']['duration_in_month'] = $duration_in_month;
        $json_data['Sale']['installment'] = $this->formatNumber($mth_inst, 'money');
        $json_data['Sale']['last_paid_date'] = $last_dt;
        $json_data['Sale']['next_credit_date'] = $next_credit_date;
        $json_data['Sale']['total_installment'] = $this->formatNumber($totalpayment, 'money');
        $json_data['Sale']['balance'] = $this->formatNumber($bal, 'money');
        $json_data['Sale']['items'] = $items;
        $json_data['Sale']['repayment'] = $repayment;
        $json_data['vehicle_no'] = $vehicle_no;
        $json_data['pastdue'] = $this->formatNumber($tl_pastdue, 'money');
        $json_data['undue'] = $this->formatNumber($tl_undue, 'money');
        $json_data['pastdue_raw'] = $tl_pastdue;
        $json_data['undue_raw'] = $tl_undue;
        $json_data['tl_expected'] = $tl_expected;
        $json_data['tl_actual'] = $tl_actual;
        $json_data['tl_outstanding'] = $tl_outstanding;

        return $json_data;
    }


    function get_amortize_repayment($data_id = null)
    {
        ClassRegistry::init('Sale');

        /** Loading */
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit', 'Sale.discount', 'Sale.payment_type', 'Sale.currency', 'Sale.comments'),
            'conditions' => array('Sale.id' => $data_id),
            'contain' => array(
                'Customer',
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id', 'SaleItem.quantity'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount', 'SaleCreditPayment.pay_date'),
                )
            ),
            'recursive' => 2
        ));

        $is_outright = false;
        $opening_bal = doubleval($data['Sale']['opening_bal']);
        $purchase_type = $data['Sale']['purchase_type'];
        //IF the customer made outright payment
        if($opening_bal == $data['Sale']['deposit']){
            $opening_bal = 0.00;
            $is_outright = true;
        }

        //Items
        $items = '';
        foreach ($data['SaleItem'] as $item) {
            $items .= $item['Item']['name'] . '(qty x' . $item['quantity'] . '),&nbsp;&nbsp;';
        }

        //Monthly Installments
        $duration_in_month = $data['Sale']['duration_in_month'];
        $vehicle_no = $data['Sale']['vehicle_no'];
        //$data['Sale']['opening_bal']
        // $mth_inst = (doubleval($data['Sale']['opening_bal'])) / intval($duration_in_month);
        //$mth_inst = number_format($mth_inst, 2, '.', '');

        $mth_inst = $this->getMonthlyPayment($data['Sale']['interest'], $duration_in_month, $opening_bal, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places'],$purchase_type);

        $interest_ratio = $this->getRate($data['Sale']['interest'], $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places']);

        //Next month credit
        if ($data['SaleCreditPayment']) {
            $last_dt = $data['SaleCreditPayment'][0]['pay_date']; // this is sorted on id desc, so the first index[0] is the last paid date
        }
        else {
            $last_dt = $data['Sale']['purchased_date'];
        }
        $d = new DateTime($last_dt);
        $d->modify('next month');
        $next_credit_date = $d->format('Y-m-d');

        //Total Creidt Payment
        $totalpayment = 0.00;
        foreach ($data['SaleCreditPayment'] as $payment) {
            $totalpayment += doubleval($payment['paid_amount']);
        }

        // Outstanding balance
        $bal = (doubleval($opening_bal) - $totalpayment);

        if($is_outright){
            $purchase_dt = $data['Sale']['purchased_date'];
            $tl_expected = 0.00;
            $tl_actual = 0.00;
            $tl_outstanding = 0.00;
            $count = 1;

            $n_dt = new DateTime($purchase_dt);
            $month_year = $n_dt->format('M-y');
            $month_year2 = $n_dt->format('n-Y');
            $paid_amt = $this->formatNumber($data['Sale']['deposit']);
            $expected = $this->formatNumber($data['Sale']['opening_bal']);
            $outstanding = $this->formatNumber($expected - $paid_amt);
            $arr = array(
                $month_year,
                $this->__add_ordinal_suffix($count) . " month",
                $this->formatNumber($expected, 'money'),
                $this->formatNumber($paid_amt, 'money'),
                $this->formatNumber($outstanding, 'money')
            );
            $repayment[] = $arr;
            $arr2 = array(
                $month_year2,
                $this->formatNumber($expected),
                $this->formatNumber($paid_amt),
                $this->formatNumber($outstanding)
            );
            $rep_arr[] = $arr2;

            $tl_expected = $tl_expected + $expected;
            $tl_actual = $tl_actual + $paid_amt;
            $tl_outstanding = $tl_outstanding + $outstanding;


            $arr = array('', "<b>TOTAL</b>", "<b>" . $this->formatNumber($tl_expected, 'money') . "</b>", "<b>" . $this->formatNumber($tl_actual, 'money') . "</b>", "<b>" . $this->formatNumber($tl_outstanding, 'money') . "</b>");
            $repayment[] = $arr;
        }
        else{
            $repayment = array();
            $rep_arr = array();
            //Repayment formatting
            if ($duration_in_month > 0) { //Purchase date and end date are not the same
                $new_dt = new DateTime($data['Sale']['purchased_date']);
                $new_dt->modify('next month');
                $start_date = $new_dt->format('Y-m-d'); //Smaller date
                $end_date = $data['Sale']['end_date']; //Bigger date
                $diff_in_month = $this->count_months_between_dates($start_date, $end_date);
                $dates_arr = array($start_date);
                if ($diff_in_month > 0) {
                    $date_increment = $start_date;
                    for ($x = 1; $x <= $diff_in_month; $x++) {
                        $dt = new DateTime($date_increment);
                        $dt->modify('next month');
                        $dates_arr[] = $date_increment = $dt->format('Y-m-d');
                    }
                }

                $tl_expected = 0.00;
                $tl_actual = 0.00;
                $tl_outstanding = 0.00;
                $count = 1;

                $new_opbl = $opening_bal;//For amortization
                $tl_expected_interest = 0.00;
                $tl_actual_interest = 0.00;
                $tl_principal = 0.00;
                $tl_amor_balance = 0.00;

                foreach ($dates_arr as $date_str) {
                    $n_dt = new DateTime($date_str);
                    $rest = substr($date_str, 0, -3);
                    $amt_to_pay = 0.00;
                    $payment_made = false;
                    foreach ($data['SaleCreditPayment'] as $payment) {
                        $y_m = substr($payment['pay_date'], 0, -3);
                        if ($rest == $y_m) {
                            $amt_to_pay = doubleval($payment['paid_amount']);
                            $payment_made = true;
                        }
                    }

                    /*************************************** Amortizing  */
                    $payment_amount = $mth_inst;
                    $inerest = $new_opbl * $interest_ratio;
                    $principal = $payment_amount - $inerest;
                    $balance = $bal1 = $new_opbl - $principal;
                    $bal1 = $this->formatNumber($bal1);

                    if ($bal1 == -0.0) {
                        $balance = 0.0;
                    }

                    $row = array();
                    //$row['period'] = $count;
                    //$row['payment_amount'] = $this->formatNumber($mth_inst, 'money');
                    $expected_interest = $inerest;
                    $actual_interest = 0.00;
                    if($payment_made){
                        $actual_interest = $inerest;
                    }
                    $amor_principal = $principal;
                    $amor_balance = $balance;

                    //Reset the new opening bal
                    $new_opbl = $balance;

                    $tl_expected_interest = $tl_expected_interest + $inerest;
                    $tl_actual_interest = $tl_actual_interest + $actual_interest;
                    $tl_principal = $tl_principal + $amor_principal;
                    $tl_amor_balance = $tl_amor_balance + $amor_balance;

                    /**************************************** End of Amortizing */

                    $month_year = $n_dt->format('M-y');
                    $month_year2 = $n_dt->format('n-Y');
                    $month_year3 = $n_dt->format('M-Y');
                    $paid_amt = $this->formatNumber($amt_to_pay);
                    $expected = $this->formatNumber($mth_inst);
                    $outstanding = $this->formatNumber($mth_inst - $paid_amt);
                    $arr = array(
                        $month_year3,
                        $this->__add_ordinal_suffix($count) . " month",
                        $this->formatNumber($expected, 'money'),
                        $this->formatNumber($paid_amt, 'money'),
                        $this->formatNumber($outstanding, 'money'),
                        $this->formatNumber($expected_interest, 'money'),//Expected Interest
                        $this->formatNumber($actual_interest, 'money'),//Actual Interest == Expected interest if payment was made
                        $this->formatNumber($amor_principal, 'money'),
                        $this->formatNumber($amor_balance, 'money')

                    );
                    $repayment[] = $arr;
                    $arr2 = array(
                        $month_year2,
                        $this->formatNumber($expected),
                        $this->formatNumber($paid_amt),
                        $this->formatNumber($outstanding),
                        $this->formatNumber($expected_interest),//Expected Interest
                        $this->formatNumber($actual_interest),//Actual Interest == Expected interest if payment was made
                        $this->formatNumber($amor_principal),
                        $this->formatNumber($amor_balance)
                    );
                    $rep_arr[] = $arr2;

                    $tl_expected = $tl_expected + $expected;
                    $tl_actual = $tl_actual + $paid_amt;
                    $tl_outstanding = $tl_outstanding + $outstanding;

                    $count++;
                }

                $arr = array(
                    '',
                    "<b>TOTAL</b>", "<b>" . $this->formatNumber($tl_expected, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_actual, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_outstanding, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_expected_interest, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_actual_interest, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_principal, 'money') . "</b>",
                    "<b>" . $this->formatNumber($tl_amor_balance, 'money') . "</b>"
                );
                $repayment[] = $arr;
            }
        }

        //debug($rep_arr);

        //find undue and past due
        $pastdue_amt = array();
        $undue_amt = array();
        //$now = strtotime(date('M-y'));
        $now_month = intval(date('n'));
        $now_year = intval(date('Y'));

        foreach ($rep_arr as $key => $value) {
            $dt_arr = explode('-', $value[0]);
            $dt_month = intval($dt_arr[0]);
            $dt_year = intval($dt_arr[1]);

            $topay = $value[1]; //amtpaid
            $amtpaid = floatval($value[2]); //amtpaid
            $outstanding_bal = floatval($value[3]); //
            //echo "$dt <= $now </ br>";
            if ($dt_year < $now_year) { //pastdue
                if ($amtpaid == 0.00) {
                    $pastdue_amt[] = $topay;
                }
                elseif($amtpaid > 0 ){
                    if($amtpaid == $topay){
                        $pastdue_amt[] = 0;
                    }
                    else{
                        $pastdue_amt[] = $outstanding_bal;
                    }
                }
            }
            elseif (($dt_year == $now_year)) {
                if (($dt_month < $now_month)) { //pastdue
                    if ($amtpaid == 0.00) {
                        $pastdue_amt[] = $topay;
                    }
                    elseif($amtpaid > 0 ){
                        if($amtpaid == $topay){
                            $pastdue_amt[] = 0;
                        }
                        else{
                            $pastdue_amt[] = $outstanding_bal;
                        }
                    }
                }
                elseif (($dt_month >= $now_month) && $amtpaid == 0.00) { //undue
                    $undue_amt[] = $topay;
                }
            }
            else { //undue
                if ($amtpaid == 0.00) {
                    $undue_amt[] = $topay;
                }
            }
        }

        $tl_pastdue = array_sum($pastdue_amt);
        $tl_undue = array_sum($undue_amt);

        $json_data = $data;
        $json_data['SaleCreditPayment'] = '';
        $json_data['Sale']['duration_in_month'] = $duration_in_month;
        $json_data['Sale']['installment'] = $this->formatNumber($mth_inst, 'money');
        $json_data['Sale']['last_paid_date'] = $last_dt;
        $json_data['Sale']['next_credit_date'] = $next_credit_date;
        $json_data['Sale']['total_installment'] = $this->formatNumber($totalpayment, 'money');
        $json_data['Sale']['balance'] = $this->formatNumber($bal, 'money');
        $json_data['Sale']['items'] = $items;
        $json_data['Sale']['repayment'] = $repayment;
        $json_data['vehicle_no'] = $vehicle_no;
        $json_data['pastdue'] = $this->formatNumber($tl_pastdue, 'money');
        $json_data['undue'] = $this->formatNumber($tl_undue, 'money');
        $json_data['pastdue_raw'] = $tl_pastdue;
        $json_data['undue_raw'] = $tl_undue;
        $json_data['tl_expected'] = $tl_expected;
        $json_data['tl_actual'] = $tl_actual;
        $json_data['tl_outstanding'] = $tl_outstanding;

        return $json_data;
    }


    function get_aging_analysis_data($data_id = null)
    {
        ClassRegistry::init('Sale');

        /** Loading */
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit', 'Sale.discount', 'Sale.payment_type', 'Sale.currency', 'Sale.comments'),
            'conditions' => array('Sale.id' => $data_id),
            'contain' => array(
                'Customer',
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id', 'SaleItem.quantity'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount', 'SaleCreditPayment.pay_date'),
                )
            ),
            'recursive' => 2
        ));

        //Monthly Installments
        $duration_in_month = $data['Sale']['duration_in_month'];
        //IF the customer made outright payment
        $opening_bal = $data['Sale']['opening_bal'];
        if($opening_bal == $data['Sale']['deposit']){
            $opening_bal = 0.00;
        }
        $purchase_type = $data['Sale']['purchase_type'];
        $mth_inst = $this->getMonthlyPayment($data['Sale']['interest'], $duration_in_month, $opening_bal, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places'],$purchase_type);


        //Next month credit
        if ($data['SaleCreditPayment']) {
            $last_dt = $data['SaleCreditPayment'][0]['pay_date']; // this is sorted on id desc, so the first index[0] is the last paid date
        }
        else {
            $last_dt = $data['Sale']['purchased_date'];
        }
        $d = new DateTime($last_dt);
        $d->modify('next month');
        $next_credit_date = $d->format('Y-m-d');

        $repayment = array();
        $rep_arr = array();
        //Repayment formatting
        if ($duration_in_month > 0) { //Purchase date and end date are not the same
            $new_dt = new DateTime($data['Sale']['purchased_date']);
            $new_dt->modify('next month');
            $start_date = $new_dt->format('Y-m-d'); //Smaller date
            $end_date = $data['Sale']['end_date']; //Bigger date
            $diff_in_month = $this->count_months_between_dates($start_date, $end_date);
            $dates_arr = array($start_date);
            if ($diff_in_month > 0) {
                $date_increment = $start_date;
                for ($x = 1; $x <= $diff_in_month; $x++) {
                    $dt = new DateTime($date_increment);
                    $dt->modify('next month');
                    $dates_arr[] = $date_increment = $dt->format('Y-m-d');
                }
            }

            $tl_expected = 0.00;
            $tl_actual = 0.00;
            $tl_outstanding = 0.00;
            $count = 1;
            foreach ($dates_arr as $date_str) {
                $n_dt = new DateTime($date_str);
                $rest = substr($date_str, 0, -3);
                $amt_to_pay = 0.00;
                foreach ($data['SaleCreditPayment'] as $payment) {
                    $y_m = substr($payment['pay_date'], 0, -3);
                    if ($rest == $y_m) {
                        $amt_to_pay = doubleval($payment['paid_amount']);
                    }
                }
                $month_year = $n_dt->format('M-y');
                $month_year2 = $n_dt->format('n-Y');
                $paid_amt = $this->formatNumber($amt_to_pay);
                $expected = $this->formatNumber($mth_inst);
                $outstanding = $this->formatNumber($mth_inst - $paid_amt);
                /*$arr = array(
                    $month_year,
                    $this->__add_ordinal_suffix($count)." month",
                    $this->formatNumber($expected,'money'),
                    $this->formatNumber($paid_amt,'money'),
                    $this->formatNumber($outstanding,'money')
                );*/
                // $repayment[] = $arr;
                $arr2 = array(
                    $month_year2,
                    $this->formatNumber($expected),
                    $this->formatNumber($paid_amt),
                    $this->formatNumber($outstanding)
                );
                $rep_arr[] = $arr2;

                $tl_expected = $tl_expected + $expected;
                $tl_actual = $tl_actual + $paid_amt;
                $tl_outstanding = $tl_outstanding + $outstanding;

                $count++;
            }
            // $arr = array('',"<b>TOTAL</b>","<b>".$this->formatNumber($tl_expected,'money')."</b>","<b>".$this->formatNumber($tl_actual,'money')."</b>","<b>".$this->formatNumber($tl_outstanding,'money')."</b>");
            // $repayment[] = $arr;
        }

        //find undue and past due
        $pastdue_amt = array();
        $undue_amt = array();
        //$now = strtotime(date('M-y'));
        $now_month = intval(date('n'));
        $now_year = intval(date('Y'));

        $aging_30 = array();
        $aging_60 = array();
        $aging_90 = array();
        foreach ($rep_arr as $key => $value) {
            $dt_arr = explode('-', $value[0]);
            $dt_month = intval($dt_arr[0]);
            $dt_year = intval($dt_arr[1]);

            $topay = floatval($value[1]); //amtpaid
            $amtpaid = floatval($value[2]); //amtpaid
            $outstanding_bal = floatval($value[3]); //
            if ($dt_year < $now_year) { //90 plus days overdue
                if ($amtpaid == 0.00) {
                    $aging_90[] = $topay;
                }
                elseif($amtpaid > 0 ){
                    if($amtpaid == $topay){
                        $aging_90[] = 0;
                    }
                    else{
                        $aging_90[] = $outstanding_bal;
                    }
                }
            }
            elseif (($dt_year == $now_year)) {
                if (($dt_month < $now_month)) { //pastdue
                    $pay_me = 0.00;
                     if ($amtpaid == 0.00) {
                         $pay_me = $topay;
                     }
                     elseif($amtpaid > 0 ){
                         if($amtpaid == $topay){
                             $pay_me = 0;
                         }
                         else{
                             $pay_me = $outstanding_bal;
                         }
                     }
                    $m = $now_month - $dt_month;
                    if ($m == 1) { //30 days overdue
                        $aging_30[] = $pay_me;
                    }
                    elseif ($m == 2) { //60 days overdue
                        $aging_60[] = $pay_me;
                    }
                    elseif ($m >= 3) { //90 plus days overdue
                        $aging_90[] = $pay_me;
                    }
                }
                /*elseif(($dt_month >= $now_month) && $amtpaid == 0.00){//undue
                    $undue_amt[] = $topay;
                }*/
            }
            /*
            else{//undue
                if($amtpaid == 0.00){
                    $undue_amt[] = $topay;
                }
            }*/
        }

        $tl_aging = array(
            'aging_30' => array_sum($aging_30),
            'aging_60' => array_sum($aging_60),
            'aging_90' => array_sum($aging_90),
        );

        $json_data = $tl_aging;

        return $json_data;
    }


    function get_sales_per_item($currency=null,$start_dt=null,$end_dt=null)
    {
        ClassRegistry::init('Sale');

        /** Loading */
        $data = $this->Sale->find('all', array(
            'conditions' => array('Sale.currency' => $currency,'Sale.purchased_date >=' => $start_dt, 'Sale.purchased_date <=' => $end_dt),
            //'conditions' => array('Sale.currency' => $currency),
            'contain' => array(
                'SaleItem' => array(
                    'Item' => array(
                        'fields' => array('Item.name'),
                    )
                ),
                'SaleCreditPayment'
            ),
            'recursive' => 2
        ));

        $items = array();
        foreach($data as $value){
            $sale = $value['Sale'];
            $sale_items = $value['SaleItem'];
            $payments = $value['SaleCreditPayment'];

            $item_payments = $this->get_items_payments($sale,$sale_items,$payments);

            foreach($item_payments as $key => $value){
                if(isset($items[$key])){
                    $tl_unit_price = $items[$key]['tl_unit_price'];
                    $tl_qty = $items[$key]['tl_qty'];
                    //$tl_discount = $items[$key]['tl_discount'];
                    $tl_discount_amount = $items[$key]['tl_discount_amount'];
                    $tl_discounted_unit_price = $items[$key]['tl_discounted_unit_price'];
                    $tl_cost_price = $items[$key]['tl_cost_price'];
                    $tl_payment = $items[$key]['tl_payment'];
                    $tl_outstanding = $items[$key]['tl_outstanding'];
                }
                else{
                    $tl_unit_price = 0.00;
                    $tl_qty = 0;
                    $tl_discount_amount = 0.00;
                    $tl_discounted_unit_price = 0.00;
                    $tl_cost_price = 0.00;
                    $tl_payment = 0.00;
                    $tl_outstanding = 0.00;
                }

                $items[$key] = array(
                    'name'=> $value['name'],
                    'tl_unit_price'=> $tl_unit_price + $value['unit_price'],
                    'tl_qty'=> $tl_qty + $value['qty'],
                    'tl_discount_amount'=> $tl_discount_amount + $value['discount_amount'],
                    'tl_discounted_unit_price'=>$tl_discounted_unit_price + $value['discounted_unit_price'],
                    'tl_cost_price'=>$tl_cost_price + $value['cost_price'],
                    'tl_payment'=>$tl_payment + $value['payment'],
                    'tl_outstanding'=>$tl_outstanding + $value['outstanding']
                );
            }
        }

        $tl_unit_price = 0.00;
        $tl_qty = 0.00;
        $tl_discount_amount = 0.00;
        $tl_discounted_unit_price = 0.00;
        $tl_cost_price = 0.00;
        $tl_payment = 0.00;
        $tl_outstanding = 0.00;
        $totals = array();
        foreach($items as $key => $value){
            $tl_unit_price = $tl_unit_price + $value['tl_unit_price'];
            $tl_qty = $tl_qty + $value['tl_qty'];
            $tl_discount_amount = $tl_discount_amount + $value['tl_discount_amount'];
            $tl_discounted_unit_price = $tl_discounted_unit_price + $value['tl_discounted_unit_price'];
            $tl_cost_price = $tl_cost_price + $value['tl_cost_price'];
            $tl_payment = $tl_payment + $value['tl_payment'];
            $tl_outstanding = $tl_outstanding + $value['tl_outstanding'];
        }

        $totals = array(
            'name'=> '',
            'tl_unit_price'=> $tl_unit_price,
            'tl_qty'=> $tl_qty,
            'tl_discount_amount'=> $tl_discount_amount,
            'tl_discounted_unit_price'=>$tl_discounted_unit_price,
            'tl_cost_price'=>$tl_cost_price,
            'tl_payment'=>$tl_payment,
            'tl_outstanding'=>$tl_outstanding
        );


        $return = array();
        $return['items'] = $items;
        $return['totals'] = $totals;
        return $return;
    }


    function get_items_payments($sale,$sale_items,$payments){

        $currency = $sale['currency'];
        $opening_bal = doubleval($sale['opening_bal']);
        //IF the customer made outright payment
        if($opening_bal == $sale['deposit']){
            $opening_bal = 0.00;
        }

        $duration_in_month = intval($sale['duration_in_month']);
        $interest = doubleval($sale['interest']);
        $interest_ratio = $this->getRate($interest, $sale['tenor'],$sale['interest_rate_decimal_places']);

        $purchase_type = $sale['purchase_type'];
        $mth_inst = $this->getMonthlyPayment($interest, $duration_in_month, $opening_bal, $sale['tenor'],$sale['interest_rate_decimal_places'],$purchase_type);


        // Amortize the sale to know the expected overall interest
        $new_opbl = $opening_bal;
        $amor = array();

        $tl_interest_paid = 0.00;
        $tl_principal = 0.00;

        for ($x = 1; $x <= $duration_in_month; $x++) {
            $payment_amount = $mth_inst;
            $inerest = $new_opbl * $interest_ratio;
            $principal = $payment_amount - $inerest;
            $balance = $bal1 = $new_opbl - $principal;
            $bal1 = $this->formatNumber($bal1);

            if ($bal1 == -0.0) {
                $balance = 0.0;
            }

            $tl_interest_paid = $tl_interest_paid + $inerest;
            $tl_principal = $tl_principal + $principal;

            //Reset the new opening bal
            $new_opbl = $balance;
        }
        $inerest_rate = $tl_interest_paid/$tl_principal; //rate at which each month payment contribute to the interest
        //$payment_without_interest_per_period = $tl_principal/$duration_in_month;
        //$interest_per_period = $tl_interest_paid/$duration_in_month;

        $deposit = $this->formatNumber($sale['deposit']);
        $discount = $this->formatNumber($sale['discount']);
        $tl_payments = $this->get_total_re_payments($payments,$inerest_rate);
        //$total_payment = $deposit + $tl_payments;
        $total_payment = $tl_payments;

        $tl_cost_price = 0.00;
        $items = array();
        foreach($sale_items as $value){
            $unit_price = $this->formatNumber($value['unit_price']);
            $qty = $this->formatNumber($value['quantity']);
            $discount_amount = ($discount/100)*$unit_price;
            $bal = $unit_price - $discount_amount; //Apply the discount on each itmem unit cost
            $cost_price = $bal * $qty;
            $items['id_'.$value['item_id']] = array(
                'name' =>$value['Item']['name'],
                'unit_price'=>$unit_price,
                'qty' =>$qty,
                'discount' =>$discount,
                'discount_amount' =>$discount_amount,
                'discounted_unit_price' =>$bal,
                'cost_price'=> $cost_price
            ) ;
            $tl_cost_price = $tl_cost_price + $cost_price;
        }

        $items_to_sort = array();
        foreach($items as $key => $value){
            //find the ratio for each items value to the overall cost price
            $item_cost_ratio =  $value['cost_price']/$tl_cost_price;
            $deposite_slice = $deposit * $item_cost_ratio;
            $items[$key]['cost_ratio'] = $item_cost_ratio;
            //$items[$key]['deposite_slice'] = $deposite_slice;
            //$items[$key]['net_cost_price'] = $value['cost_price'] - $deposite_slice;

            //$items_to_sort[$key] = $value['net_cost_price'];
            $items_to_sort[$key] = $value['cost_price'];
        }
        asort($items_to_sort);

        foreach($items_to_sort as $key => $cost_price){
            if($total_payment >= $cost_price){
                $pay = $total_payment - $cost_price;
                $outstanding = 0.00;
            }
            else{
                if($total_payment > 0){ //but if there is some left, assign what is left to the current item as pay and set total_payment to zero
                    $pay = $total_payment;
                    $outstanding = $cost_price - $total_payment;
                    $total_payment = 0.00;
                }
                elseif($total_payment == 0){
                    $pay = 0.00;
                    $outstanding = $cost_price;
                    $total_payment = 0.00;
                }
            }
            $items[$key]['payment'] = $pay;
            $items[$key]['outstanding'] = $outstanding;

        }

        return $items;
    }

    function get_total_re_payments($payments,$inerest_rate){
        $total = 0.00;
        foreach($payments as $value){
            $paid_amount = $this->formatNumber($value['paid_amount']);
            //remove the interest rate that make up the this paymnet
           // $interest_amount = $paid_amount - $inerest_rate;
           // $principal_payment = $paid_amount - $interest_amount;
            $total = $total + $paid_amount;
        }
        return $total;
    }


    function get_customers_select(){

        ClassRegistry::init('Sale');

        $customers_sales_data = $this->Sale->find('all', array(
            'fields' => array('DISTINCT Sale.customer_id'),
            'conditions' => array('Sale.deleted'=>'n','Sale.customer_id >'=>0),
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name','Customer.contact_person'),
                )
            ),
            'recursive' => 1
        ));

        $customers_sales = array();
        $customers_sales[] = array('name'=>'All', 'value'=>0);
        foreach($customers_sales_data as $data){
            $customers_sales[] = array('name'=>$data['Customer']['name'], 'value'=>$data['Customer']['id']);
        }
        return $customers_sales;
    }


    function __add_ordinal_suffix($num)
    {
        $last = substr($num, -1);
        if (strlen($num) < 2) {
            $next_to_last = 0;
        } else
        {
            $next_to_last = substr($num, -2);
        }
        if ($next_to_last >= 10 && $next_to_last < 20) {
            $suff = "th";
        } else
            if ($last == 1) {
                $suff = "st";
            } else
                if ($last == 2) {
                    $suff = "nd";
                } else
                    if ($last == 3) {
                        $suff = "rd";
                    } else
                    {
                        $suff = "th";
                    }

        return number_format($num) . $suff;
    }


    function toTitleCase($str){
        $str = ucwords(strtolower($str));
        return $str;
    }

}
